import { App } from "../App";
import { Singleton } from "./Class";

// 登陆类型 
enum LoginType{
    Unknow = -1,
    Guest = 0,
    Wechat,
    Facebook,
    Zalo,
    Max
}

export default class NativeLib extends Singleton<NativeLib>{
    constructor(){
        super();
    }

    protected onInit(){
        // IOS/Android底层回调，通过事件派发的方式来做解决系统底层和上层脱耦。
        cc.director.on('NativeMessageCall',(flag:string,data:any)=>{
            console.log(`<--------NativeMessageCall:${flag} data=${data}-------->`)
            App.Event.emit(flag,data);
        });

        if (cc.sys.isNative){
            let writePath = this.getWritablePath();
            let searchs = jsb.fileUtils.getSearchPaths() || [];
            if (!searchs.includes(writePath)){
                searchs.unshift(writePath);
                jsb.fileUtils.setSearchPaths(searchs);
                cc.sys.localStorage.setItem(App.LOCAL_KEY.WRITE_DIR,searchs);
            }
        }
    }

    /**
     * 
     * @param cmd 
     * @param data 
     * @returns 
     */
    public callNative(cmd:string,json?:any){
        if (!cc.sys.isNative) {
            return ;
        }

        if (App.Util.isEmpty(cmd)){
            console.error('NativeLib.callNative(flag is empty)');
            return ;
        }

        json = json || {data:'null'};
        if (cc.sys.OS_ANDROID == cc.sys.os) {
            jsb.reflection.callStaticMethod('org/cocos2dx/javascript/ToolHelp',
                'callNative', '(Ljava/lang/String;Ljava/lang/String;)V',cmd,JSON.stringify(json));
        } else if (cc.sys.OS_IOS == cc.sys.os) {
            jsb.reflection.callStaticMethod('AppController', 'callNative', '()V');
        }
    }

    get searchPaths():string[] { return cc.sys.isNative ? jsb.fileUtils.getSearchPaths():[]; }

    public setSearchPaths(arr:string[]):void {
        cc.sys.isNative && jsb.fileUtils.setSearchPaths(arr);
    }

    public getWritablePath():string {
        if (!cc.sys.isNative) return '';
        const nativePath = `${jsb.fileUtils.getWritablePath()}${App.ModuleName}/`;
        console.log(`native write Path : ${nativePath}`);
        return nativePath;
    }

    public isPathExist(path:string):boolean { 
        if (!cc.sys.isNative) return true;

        let isDir = path.lastIndexOf('.') < 0;
        return isDir ? jsb.fileUtils.isDirectoryExist(path) : jsb.fileUtils.isFileExist(path); 
    }

    public getStringFromFile(file:string):string { 
        const localPath = `${this.getWritablePath()}${file}`;
        console.log(`read local file:${localPath}`);
        return (this.isPathExist(localPath) && cc.sys.isNative) ? jsb.fileUtils.getStringFromFile(localPath) : null;
    }


    /**
     * 弹出系统对话框，一般用来调试
     * @param msg 
     * @param title 
     * @returns 
     */
    public showSysAlert(msg:string, title:string = 'tips') {
        if (!App.isDebug) {
            console.log(msg);
            return;
        }

        if (cc.sys.isNative) {
            this.callNative('showAlertDialog',JSON.stringify({title:title,msg:msg}));
        } else App.MessageBox(`${title}|${msg}`);
    }

    /**
     * 横竖屏切换
     * @param flag 
     * @param callFun 
     * @param delay 
     */
    public setOrientation(flag, callFun, delay = 100) {
        const desSize = cc.view.getDesignResolutionSize();
        const wndSize = cc.view.getFrameSize();
        const resolution = cc.view.getResolutionPolicy();
        if (cc.sys.isNative) {
            this.callNative('setOrientation',JSON.stringify({direction:flag}));
        } else {
            cc.view.setOrientation(flag !== 2 ? cc.macro.ORIENTATION_LANDSCAPE : cc.macro.ORIENTATION_PORTRAIT);
        }

        // 防止底层多线程影响，延迟0.1秒设置下窗体尺寸
        setTimeout(() => {
            let _ws = flag === 2 ? cc.size(wndSize.height, wndSize.width) : cc.size(wndSize.width, wndSize.height);
            let _ds = flag === 2 ? cc.size(desSize.height, desSize.width) : cc.size(desSize.width, desSize.height);
            let _rp = flag === 2 ? cc.ResolutionPolicy.FIXED_WIDTH : resolution;
            if (!cc.sys.isNative && !App.wideScreen) {
                _ws.width *= 0.64;
                _ws.height *= 0.64;
                _ds.width *= 0.64;
                _ds.height *= 0.64;
            }
            cc.view.setFrameSize(_ws.width, _ws.height);
            cc.view.setDesignResolutionSize(_ds.width, _ds.height, _rp);
            callFun && callFun(flag, _ws);
        }, delay);
    }
}